import os
import sys
from db import create_db
from extractor import Extractor
from tkinter import filedialog, messagebox
import tkinter as tk
from tqdm import tqdm
from models import User, Info

file_path = None


def load_files(file_dir):
    pdf_files = []
    for root, dirs, files in os.walk(file_dir):
        for file_ in files:
            path = os.path.join(root, file_)
            if os.path.isfile(path) and path.endswith('.pdf'):
                pdf_files.append(path)
    return pdf_files


def get_file_path(root):
    global file_path
    file_path = filedialog.askdirectory()
    if not file_path:
        messagebox.showerror(messagebox='你没有选择文件夹')
        sys.exit()
    else:
        file_path = os.path.abspath(file_path)
    root.destroy()


def main():
    global file_path
    root = tk.Tk()
    root.geometry('300x300')
    tk.Label(root, text='选择pdf文件夹路径', font=('microsoft yahei', 12, 'bold')).place(x=100, y=100)
    tk.Button(root, text='浏览...', font=('microsoft yahei', 12, 'bold'), command=lambda: get_file_path(root)).place(
        x=150, y=200)
    root.mainloop()

    if file_path is None or not os.path.isdir(file_path):
        messagebox.showerror(message='未选择有效的PDF文件夹！')
        sys.exit()
    pdf_files = load_files(file_path)
    keywords_file = 'keywords.txt'
    if not os.path.isfile(keywords_file):
        messagebox.showerror(message='没有找到关键词文件：keywords.txt')
        sys.exit()
    db = create_db()
    db.init_db()
    for file_ in tqdm(pdf_files):
        ex = Extractor(file_, keywords_file)
        try:
            person_info = ex.parse_person_info()
            user = User(cCardNo=person_info.get('体检号', ''),
                        cName=person_info.get('姓名', ''),
                        cSex=person_info.get('性别', ''),
                        dBornDate=person_info.get('出生日期', ''),
                        iAges=person_info.get('年龄', 0),
                        cIdCard=person_info.get('身份证号', ''),
                        dAffirmdate=person_info('体检日期', ''),
                        cAddress=file_)
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            messagebox.showerror(message=f'解析文件{file_}个人信息出错！error:{e}')
        try:
            proj_info = ex.parse_project_info_aikang()
        except Exception as e:
            messagebox.showerror(message=f'解析文件{file_}科室信息出错！error:{e}')

    root.mainloop()


if __name__ == '__main__':
    main()
